'use strict'

//node: 开头表示导入Node.js官方模块
const http = require('node:http')

//定义一个路由表
let routeTable = {
  GET: {
    '/' : (req, res) => {
      res.end('This is home page.')
    }
  },
  POST: {
    '/data': (req, res) => {
      //bodyData会被挂载到req上，作为一个属性
      res.end(req.bodyData)
    },
    '/back': (req, res) => {
      res.write('123')
      res.write('23456')
      res.end('ok,end.')
    },
    '/image': (req, res) => {
      console.log(req.bodyData.toString())
      res.end('ok')
    }
  },
  PUT: {},
  DELETE: {}
}


let serv = http.createServer((req, res) => {
  //输出测试
  console.log(req.headers, req.method, req.url)

  req.on('error', err => {
    console.error(err)
    //出错则销毁连接
    !res.destroyed && res.destroy()
  })

  let bodyLength = 0
  let bodyBuffers = []
  let bodyData = null

  //只有P D开头的请求方法才被允许提交数据
  if (['P', 'D'].indexOf(req.method[0])>=0) {
    //接收body数据，data 是Buffer实例
    req.on('data', data => {
      bodyBuffers.push(data)
      bodyLength += data.length
    })
  } else {
    req.on('data', data => {
      if (data && data.length > 0) {
        res.destroy();
      }
    })
  }

  //解析url并匹配路由表 ? a=1&b=2&c=3
  let url_arr = req.url.split('?')
  let routepath = url_arr[0]
  
  //查询是否存在对应的方法
  let func = null
  if (routeTable[req.method] 
    && routeTable[req.method][routepath])
  {
    func = routeTable[req.method][routepath]
  }
  //说明找不到对应的处理方法
  if (!func) {
    if (!res.destroyed) {
      res.statusCode = 404
      res.end('not found')
    }
    return;
  }

  req.on('end', () => {
    if (bodyLength > 0) {
      bodyData = Buffer.concat(bodyBuffers, bodyLength)
      //不再引用开始的buffers，这些数据后续会被垃圾回收
      bodyBuffers = []
    }
    req.bodyData = bodyData
    //执行路由对应的请求函数
    func(req, res)
  })

})

serv.listen(3003)
